package com.tianyalei.wolf.mddesignlib.utils;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.FragmentTransaction;

import java.util.ArrayList;

/**
 * Created by Bo on 2016/4/7.
 */
public class FragmentUtil {
    private Activity mActivity;
    FragmentManager manager;
    FragmentTransaction transaction;
    private int size;
    private int mCurrentIndex = 0;

    public FragmentUtil(Activity a) {
        mActivity = a;
        manager = mActivity.getFragmentManager();

    }

    public void setData(int containId, Fragment... data) {
        size = data.length;
        transaction = manager.beginTransaction();
        for (int i = 0; i < size; i++) {
            transaction.add(containId, data[i], i + "");
            transaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
            if (0 == i) {
                transaction.show(data[i]);
            } else {
                transaction.hide(data[i]);
            }
        }
        // 如果你试图在那个点之后提交, 会抛出一个异常.这是因为如果activity需要被恢复, 提交之后的状态可能会丢失.对于你觉得可以丢失提交的状况, 使用 commitAllowingStateLoss().
        transaction.commit();
        //立即执行
        //manager.executePendingTransactions();
    }

    public void setData(int containId, ArrayList<Fragment> list) {
        size = list.size();
        transaction = manager.beginTransaction();
        for (int i = 0; i < size; i++) {
            transaction.add(containId, list.get(i), i + "");

        }
        transaction.commit();
    }

    public Fragment getCurrent() {
        return manager.findFragmentByTag(mCurrentIndex + "");
    }

    public Fragment getIndexFragment(int index) {
        return manager.findFragmentByTag(index + "");
    }

    public void addFragment(int containId, Fragment... data) {
        transaction = mActivity.getFragmentManager().beginTransaction();
        for (int i = 0; i < data.length; i++) {
            int tag = size + i;
            transaction.add(containId, data[i], tag + "");
            if (0 == i) {
                transaction.show(data[i]);
                mCurrentIndex = tag;
            } else {
                transaction.hide(data[i]);
            }
        }
        size = size + data.length;
        transaction.commit();
    }

    public void setCurrent(int index) {
        mCurrentIndex = index;
        transaction = manager.beginTransaction();
        for (int i = 0; i < size; i++) {
            Fragment fragment = manager.findFragmentByTag(i + "");
            if (index == i) {
                transaction.show(fragment);
            } else {
                transaction.hide(fragment);
            }
        }
        //replace 有用
        //transaction.setCustomAnimations(R.animator.fade_in, R.animator.fade_out);
        transaction.commit();
    }
}
